//
//  WLMessageController.m
//  WanLian
//
//  Created by xz on 2018/9/6.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLMessageController.h"
#import "WLMessageCell.h"
#import "WLMsgModel.h"
#import "WLSystemMsgVController.h"
#import "WLMessageDetailController.h"
#import "UITabBar+WLTabbarBadge.h"
#import "AppDelegate.h"
#import "WLWebViewController.h"
#import "UIScrollView+EmptyDataSet.h"

@interface WLMessageController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UIButton *btnReaded;
@property (nonatomic, strong) UITableView *tableMessage;
@property (nonatomic, strong) NSMutableArray    *arrMsgs;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger systemUnReadMsgCount;

@end

@implementation WLMessageController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSInteger unreadNum = [[NSUserDefaults standardUserDefaults] integerForKey:UNREAD_MSG_NUM];
    if (unreadNum<1)
    {
        _btnReaded.enabled = NO;
//        [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kHasReadedMessageNofication object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的消息";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMessageState) name:kHasReadedMessageNofication object:nil];
    _btnReaded = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    _btnReaded.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
    [_btnReaded setTitleColor:wlblueColor forState:UIControlStateNormal];
    [_btnReaded setTitleColor:wlUnderlineColor forState:UIControlStateDisabled];
    [_btnReaded setTitle:@"全部标为已读" forState:UIControlStateNormal];
    [_btnReaded addTarget:self action:@selector(readedAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithCustomView:_btnReaded];
    self.navigationItem.rightBarButtonItem = rightBar;
    
    _pageNum = 1;
    _arrMsgs = [[NSMutableArray alloc] init];
    _tableMessage = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableMessage.delegate = self;
    _tableMessage.dataSource = self;
    _tableMessage.rowHeight  = WLScaleX(70);
//    _tableMessage.separatorColor = HPBoardColor;
//    _tableMessage.backgroundColor = HPLightLineColor;
    if (@available(iOS 11.0, *)) {
        _tableMessage.estimatedSectionHeaderHeight = 0;
        _tableMessage.estimatedSectionFooterHeight = 0;
    }
    _tableMessage.tableFooterView = [UIView new];
    [self.view addSubview:_tableMessage];
    WLWkSelf
    [_tableMessage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    self.tableMessage.emptyDataSetSource = self;
    self.tableMessage.emptyDataSetDelegate = self;
    
    _tableMessage.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.tableMessage.mj_footer = nil;
        [weakSelf.arrMsgs removeAllObjects];
        weakSelf.pageNum = 1;
        [self sendReqeust];
    }];
    [self sendReqeust];
    
}
- (void)sendReqeust {
    [self reqNewSystemMsg];
    [self reqUserMsg];
}
- (void)refreshMessageState {
    WLMsgModel *model = self.arrMsgs.firstObject;
    if (model) {
        if (self.systemUnReadMsgCount > 1) {
            self.systemUnReadMsgCount --;
        } else {
            if (model) {
                model.hasLook = 1;
            }
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableMessage reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
        }
    }
    
}
- (void)readedAction
{
//    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    UITabBarController *tabbarController = (UITabBarController *)appDelegate.wlTabbarController;
//    [tabbarController.tabBar hideBadgeOnItemIndex:2];
    WLWkSelf;
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/update/all" withParamsDic:nil success:^(NSDictionary *successDict) {
        [weakSelf.tableMessage.mj_header beginRefreshing];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:UNREAD_MSG_NUM];
        weakSelf.btnReaded.enabled = NO;
        [weakSelf.tabBarController.tabBar hideBadgeOnItemIndex:2];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)addMsgFooterRefresh
{
    WLWkSelf
    _tableMessage.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqUserMsg];
    }];
}

- (void)reqNewSystemMsg
{
    WLWkSelf;
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/system/new" withParamsDic:nil success:^(NSDictionary *successDict) {
        WLMsgModel *msgModel = [WLMsgModel mj_objectWithKeyValues:successDict[@"object"]];
        if (msgModel) {
            [weakSelf.arrMsgs insertObject:msgModel atIndex:0];
            [weakSelf.tableMessage reloadData];
            [self reqNewSystemMsgCount];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:_tableMessage.mj_header.isRefreshing==NO?self.view:nil];
}
- (void)reqNewSystemMsgCount
{
    WLWkSelf;
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/system/count" withParamsDic:nil success:^(NSDictionary *successDict) {
        self.systemUnReadMsgCount = [[successDict objectForKey:@"count"] integerValue];
        if (self.systemUnReadMsgCount > 0) {
            WLMsgModel *fisrtModel = self.arrMsgs.firstObject;
            fisrtModel.hasLook = 0;
            [weakSelf.tableMessage reloadData];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:nil];
}

- (void)reqUserMsg
{
    WLWkSelf
    NSDictionary *params = @{@"page":@(_pageNum),@"num":@10};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/list/user" withParamsDic:params success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tableMessage.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.pageNum==1&&productCount>10)
        {
            [strongSelf addMsgFooterRefresh];
        }
        NSArray *arrPros = [WLMsgModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrMsgs addObjectsFromArray:arrPros];
            if (strongSelf.arrMsgs.count >= productCount) {
                [strongSelf.tableMessage.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tableMessage.mj_footer endRefreshing];
            }
            [strongSelf.tableMessage reloadData];
        }
        else
        {
            [strongSelf.tableMessage.mj_footer endRefreshingWithNoMoreData];
        }
        strongSelf.pageNum += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tableMessage.mj_header endRefreshing];
        [weakSelf.tableMessage.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tableMessage.mj_header endRefreshing];
        [weakSelf.tableMessage.mj_footer endRefreshing];
    } inView:nil];
}

#pragma mark - UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(20);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrMsgs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    static NSString *strMsgCell = @"strMsgCell";
    WLMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:strMsgCell];
    if (!cell) {
        cell = [[WLMessageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strMsgCell];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    WLMsgModel *msgModel = self.arrMsgs[row];
    if (row==0&&[msgModel.sourceType isEqualToString:@"NOTICE_SYSTEM"])
    {
        cell.btnHead.backgroundColor = wlUIColorRGB(0x29A8FA);
        [cell.btnHead setImage:[UIImage imageNamed:@"msg_system"] forState:UIControlStateNormal];
        cell.labTitle.text = @"系统公告";
        cell.labDetail.text = msgModel.title;
        cell.ivLink.hidden = YES;
        cell.labDetail.textColor = wlLightTextColor;
    }
    else
    {
        cell.btnHead.backgroundColor = wlUIColorRGB(0xFFBA20);
        [cell.btnHead setImage:[UIImage imageNamed:@"msg_common"] forState:UIControlStateNormal];
        cell.labTitle.text = msgModel.title;
        cell.labDetail.textColor = wlLightTextColor;
        if (msgModel.url.length>5) {
            cell.labDetail.text = @"打开链接";
            cell.labDetail.textColor = wlUIColorRGB(0xFFBA20);
            cell.ivLink.hidden = NO;
        }
        else
        {
            cell.labDetail.text = msgModel.content;
            cell.ivLink.hidden = YES;
        }
    }
    
    cell.labTime.text = [WLCommonTool timeIntervalDescription:msgModel.noticeTime];
    if (msgModel.hasLook==1)
    {
        cell.vUnread.hidden = YES;
    }
    else
    {
        cell.vUnread.hidden = NO;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WLMsgModel *model = self.arrMsgs[indexPath.row];
    if (indexPath.row==0&&[model.sourceType isEqualToString:@"NOTICE_SYSTEM"])
    {
        WLSystemMsgVController *systemMsgController = [[WLSystemMsgVController alloc] init];
        [self.navigationController pushViewController:systemMsgController animated:YES];
    }
    else if (model.url.length>7)
    {
        WLWebViewController *webView = [[WLWebViewController alloc] init];
        webView.urlStr = model.url;
        webView.titleStr = model.title;
        webView.msgId = model.msgId;
        model.hasLook = 1;
        [self.navigationController pushViewController:webView animated:YES];
    }
    else
    {
        WLMessageDetailController *msgDetailController = [[WLMessageDetailController alloc] init];
        msgDetailController.messageInfo = model;
        [self.navigationController pushViewController:msgDetailController animated:YES];
        model.hasLook = 1;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - DZNEmpty
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
//    return [UIImage imageNamed:@"no_msg"];
//}
//
//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
//    NSString *title = @"还没有消息哦~";
//    NSDictionary *attributes = @{
//                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
//                                 NSForegroundColorAttributeName:wlDarkGrayColor
//                                 };
//    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
//}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
//    UIView *noMsgView1= [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, _tableMessage.bounds.size.height)];
//    noMsgView1.backgroundColor = wlRedColor;
//    UIButton *btnHead1 = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(17), WLScaleX(36), WLScaleX(36))];
//    btnHead1.userInteractionEnabled = NO;
//    btnHead1.backgroundColor = wlUIColorRGB(0x29A8FA);
//    [btnHead1 setImage:[UIImage imageNamed:@"msg_system"] forState:UIControlStateNormal];
//    [noMsgView1 addSubview:btnHead1];
//    btnHead1.layer.cornerRadius = WLScaleX(18);
//    btnHead1.layer.masksToBounds = YES;
//    NSLayoutConstraint *heightConstraint1 = [NSLayoutConstraint constraintWithItem:noMsgView1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:_tableMessage.bounds.size.height];
//    [noMsgView1 addConstraint:heightConstraint1];
//    return noMsgView1;
    UIView *noMsgView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, _tableMessage.bounds.size.height)];
//    UIImageView *ivHead = [[UIImageView alloc] init];
    
    UIButton *btnHead = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(37), WLScaleX(36), WLScaleX(36))];
    btnHead.userInteractionEnabled = NO;
    btnHead.backgroundColor = wlUIColorRGB(0x29A8FA);
    [btnHead setImage:[UIImage imageNamed:@"msg_system"] forState:UIControlStateNormal];
    [noMsgView addSubview:btnHead];
    btnHead.layer.cornerRadius = WLScaleX(18);
    btnHead.layer.masksToBounds = YES;
//    [btnHead mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(noMsgView.mas_left).offset(WLScaleX(16));
//        make.top.equalTo(noMsgView.mas_top).offset(WLScaleX(27));
//        make.size.mas_equalTo(CGSizeMake(WLScaleX(36), WLScaleX(36)));
//    }];
    
    UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+WLScaleX(48), WLScaleX(35), WLScaleX(180), WLScaleX(20))];
    labTitle.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labTitle.textColor = wlBlackColor;
    labTitle.text = @"系统公告";
    [noMsgView addSubview:labTitle];
    
    UILabel *labDetail = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+WLScaleX(48), WLScaleX(55), WLScaleX(250), WLScaleX(20))];
    labDetail.font = [WLCommonTool fontTypePingFangSCMedium:11];
    labDetail.textColor = wlLightTextColor;
    labDetail.text = @"当前没有系统公告呢";
    [noMsgView addSubview:labDetail];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(90), WIDTH_SCREEN_WL-WLScaleX(16), WLScaleX(1))];
    lineView.backgroundColor = wlUIColorRGB(0xF2F2F2);
    [noMsgView addSubview:lineView];
    
    UIImageView *ivNoTip = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no_msg"]];
    ivNoTip.center = CGPointMake(noMsgView.center.x, noMsgView.center.y-WLScaleX(30));
    [noMsgView addSubview:ivNoTip];
    
    UILabel *labTip = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(ivNoTip.frame)+WLScaleX(20), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(30))];
    labTip.textAlignment = NSTextAlignmentCenter;
    labTip.font = [WLCommonTool fontTypePingFangSCRegular:17];
    labTip.textColor = wlDarkGrayColor;
    labTip.text = @"还没有消息哦~";
    [noMsgView addSubview:labTip];
    
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:noMsgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:_tableMessage.bounds.size.height];
    [noMsgView addConstraint:heightConstraint];
    
    return noMsgView;
}

//- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
//{
//    return 0;
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
